import CommonUtil from './common';
function getDate(value){
  //handle undefined null
  if(!value) return null;
  if(typeof value == "object"){
    if(value.getFullYear){
      //handle date
      var date = value;
    }else if(value.time){
      //handle {time:58566888,......}
      date = new Date(value.time);
    }else{
      return null;
    }
  }else if(typeof value == "number" || typeof value == 'string'){
    //handle 45345345 '2020-11-11 11:11:11'
    date = new Date(value);
  }else{
    return null;
  }
  return date;
}
export default{
	format(value,str,unPaddingZero){
		var date = getDate(value);
	  if(!date) return '';
	  str = str || "yyyy-MM-dd HH:mm:ss";
	  return str.replace("yyyy",date.getFullYear())
	    .replace("MM",unPaddingZero ? (date.getMonth()+1) : CommonUtil.paddingZero(date.getMonth()+1))
	    .replace("dd",unPaddingZero ? date.getDate() : CommonUtil.paddingZero(date.getDate()))
	    .replace("HH",unPaddingZero ? date.getHours() : CommonUtil.paddingZero(date.getHours()))
	    .replace("mm",unPaddingZero ? date.getMinutes() : CommonUtil.paddingZero(date.getMinutes()))
	    .replace("ss",unPaddingZero ? date.getSeconds() : CommonUtil.paddingZero(date.getSeconds()));
  },
  addDays(date, value) {
    date = new Date(date.getTime());
    date.setDate(date.getDate() + value);
    return date;
  },
  addMonths(date, value) {
    date = new Date(date.getTime());
    date.setMonth(date.getMonth() + value);
    return date;
  },
  addSeconds(date, value) {
    date = new Date(date.getTime());
    date.setSeconds(date.getSeconds() + value);
    return date;
  },
  // 获取当前周的第一天 00:00:00（从周一开始）
  getFirstDayOfWeek(date) {
    date = new Date(date.getTime());
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0); 
    let day = date.getDay();
    if (day === 1) return date;
    if (day === 0) {
      return this.addDays(date, -6);
    }
    return this.addDays(date, -(day - 1));
  },
  getDateBegin(date) {
    date = new Date(date.getTime());
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    return date;
  },
  getDateEnd(date) {
    date = new Date(date.getTime());
    date.setHours(23);
    date.setMinutes(59);
    date.setSeconds(59);
    return date;
  },
  getMonthBegin(date) {
    date = new Date(date.getTime());
    date.setDate(1);
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    return date;
  },
  getMonthEnd(date) {
    date = new Date(date.getTime());
    date.setMonth(date.getMonth() + 1);
    date = this.getMonthBegin(date);
    date.setSeconds(-1);
    return date;
  }
}